import React, { useState, useEffect } from 'react';
import { observer, inject } from 'mobx-react';
import { Button, Input, Space, Form, Select, Tabs, Radio, Upload, message, Segmented, ConfigProvider } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { uploadFile } from '../../../../apis/public/upload';
import styles from '../style/features.module.css';
import { StoreProps } from '../store';
import { getContentByFileId } from '@/apis/public/fileUpDownload';
import { Editor_Default_Directory } from '@/globals/document';
import { AssistantKeyMap } from '../store/documentStore';

const { TextArea } = Input;

const contentLengthMap = {
  'short': 1000,
  'medium': 2000,
  'long': 3000,
  1000: 'short',
  2000: 'medium',
  3000: 'long',
};

// 移除静态的modelOptions，改为从store中获取

const docType_statutory = [
  '通告', '报告', '函', '公告', '通知', '请示', '通报', '意见', '批复', '纪要'
];

const docTypes_affairs = [
  '工作总结', '学习体会', '调研报告', '工作报告', '讲话稿', '宣传稿', '新闻稿', '表扬信',
];

const Writing: React.FC<StoreProps> = ({ documentStore, proofreadStore }) => {
  const [form] = Form.useForm();
  const [tabKey, setTabKey] = useState('law');
  const [references, setReferences] = useState('');
  const [imitations, setImitations] = useState('');

  // 获取当前agent信息
  const currentAgent = documentStore.getAgentInfo(AssistantKeyMap.writing);
  const recommendedPrompts = currentAgent?.recommendedPrompts ? [currentAgent.recommendedPrompts] : [];

  // 初始化表单数据
  useEffect(() => {
    form.setFieldsValue(documentStore.documentForm);
  }, []);

  // 监听 documentForm 变化
  useEffect(() => {
    form.setFieldsValue(documentStore.documentForm);
  }, [documentStore.documentForm]);

  // 获取模型列表
  useEffect(() => {
    documentStore.fetchModelList();
  }, []);

  // 模型列表变化后，设置默认模型
  useEffect(() => {
    const options = documentStore.getModelOptions();
    if (
      options.length > 0 &&
      !documentStore.documentForm.model // 没有选中模型
    ) {
      // 设置第一个可用模型为默认值
      form.setFieldsValue({ model: options[0].value });
      documentStore.setDocumentForm({ model: options[0].value });
    }
  }, [documentStore.modelList]);

  // 监听表单值变化
  const handleFormValuesChange = (changedValues: any, allValues: any) => {
    documentStore.setDocumentForm(allValues);
  };

  const handleGenerate = (type: 'outline' | 'writing') => {
    if (!currentAgent) {
      return;
    }
    form.validateFields().then(() => {
      // 构建additionalParams对象
      const additionalParams = {
        odocTypeName: documentStore.documentForm.docType,
        topic_type: documentStore.documentForm.title,
        keywords: documentStore.documentForm.keywords,
        supplement: documentStore.documentForm.desc,
        user_type: "拟稿专员",
        page_length: contentLengthMap[documentStore.documentForm.length],
        references: references,
        imitations: imitations,
      };
      let success = false
      // 调用生成内容方法
      documentStore.generateContent({
        type,
        userMessage: documentStore.documentForm.title,
        additionalParams,
        onFinish: (text, context) => {
          success = context && context.type === "done";
        }
      }).then(() => {
        if (!success) {
          return;
        }
        setTimeout(() => {
          if (type === 'outline') {
            return;
          }
          const templateId = documentStore.documentForm.docType || 'report';
          documentStore.formatContent({ templateId });
        }, 0);
      });
    });
  };

  // Tabs内容
  const tabItems = [
    {
      key: 'law',
      label: '法定文书',
      children: (
        <Space wrap>
          {docType_statutory.map(type => (
            <Button
              key={type}
              type={documentStore.documentForm.docType === type ? 'primary' : 'default'}
              onClick={() => documentStore.setDocumentForm({ docType: type })}
              style={{ width: 60 }}
            >
              {type}
            </Button>
          ))}
        </Space>
      )
    },
    {
      key: 'affair',
      label: '事务文书',
      children: (
        <Space wrap>
          {docTypes_affairs.map(type => (
            <Button
              key={type}
              type={documentStore.documentForm.docType === type ? 'primary' : 'default'}
              onClick={() => documentStore.setDocumentForm({ docType: type })}
              style={{ width: 80 }}
            >
              {type}
            </Button>
          ))}
        </Space>
      )
    }
  ];

  const customRequest = async (options: any, type: 'references' | 'imitations') => {
    // 检查当前agent是否支持文件上传
    if (currentAgent?.fileUpload !== "1") {
      message.error('当前智能体不支持文件上传');
      if (options.onError) {
        options.onError(new Error('不支持文件上传'));
      }
      return;
    }

    try {
      // 拼接文件上传参数
      const formData = new FormData();
      formData.append('file', options.file);
      formData.append('fileName', options.file instanceof File ? options.file.name : 'unknown');
      formData.append('uid', options.file?.uid);
      formData.append('directoryId', Editor_Default_Directory.toString());
      const response = await uploadFile(formData);

      if (options.onSuccess) {
        getContent(response, type);
        options.onSuccess(response);
      }
      //文件内容提取
      //onUploadSuccess(file); // 调用上传成功回调函数
    } catch (error) {
      if (options.onError) {
        options.onError(error instanceof Error ? error : new Error('上传失败'));
      }
    }
  };

  /**
   * 文件内容提取
   * @param response
   * @param type
   */
  const getContent = async (response: any, type: 'references' | 'imitations') => {
    const fileId = response.data.page?.[0].id;
    if (fileId) {
      const res = await getContentByFileId({
        id: fileId,
        fileName: '',
        filePath: '',
        directoryId: Editor_Default_Directory,
        userId: Number(window.HubUser?.id),
        pageNo: 0,
        pageSize: 0,
        html: ''
      });
      if (res.code == 200 && res.data.success) {
        //这里不判断content为空，默认覆盖数据
        if (type === 'references') {
          setReferences(res.data.content);
        } else if (type === 'imitations') {
          setImitations(res.data.content);
        }
      }
      console.log('res', res);
    }
  }

  const removeContent = (type: 'references' | 'imitations') => {
    if (type === 'references') {
      setReferences('');
    } else if (type === 'imitations') {
      setImitations('');
    }
  }
  const beforeUpload = (file: File) => {
    // 检查当前agent是否支持文件上传
    if (currentAgent?.fileUpload !== "1") {
      message.error('当前智能体不支持文件上传');
      return Upload.LIST_IGNORE;
    }

    // 文件类型验证：只允许上传 pdf, doc, docx 文件
    const isValidFileType = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(file.type);
    if (!isValidFileType) {
      message.error('只能上传PDF、DOC或DOCX文件');
      return Upload.LIST_IGNORE; // 终止上传
    }

    return true; // 验证通过，允许上传
  };

  return (
    <>
      <div className={styles['statHub-feature-container']}>
        {currentAgent?.welcomeMessage && (
          <div className={styles['statHub-feature-welcome']}>
            {currentAgent.welcomeMessage}
          </div>
        )}
        <Form
          form={form}
          layout="vertical"
          onValuesChange={handleFormValuesChange}
          initialValues={documentStore.documentForm}
        >
          {currentAgent?.modelUsage === 'dynamic' && (
                      <Form.Item label="选择模型:" name="model" rules={[{ required: true, message: '请选择模型' }]}
            style={{ marginBottom: 12 }}>
            <Select 
              options={documentStore.getModelOptions()} 
              placeholder="请选择模型" 
              allowClear 
              loading={documentStore.loadingModelList}
            />
          </Form.Item>
          )}
          {/* 用div包裹Segmented和tabItems，添加边框和样式 */}
          <div
            className={styles['statHub-feature-container-segmented']}
          >
            <ConfigProvider
              theme={{
                components: {
                  Segmented: {
                    itemSelectedBg: '#1677ff', // 选中项背景色
                    itemSelectedColor: '#fff', // 选中项字体色
                    itemColor: '#333', // 未选中项字体色
                    itemHoverBg: '#e6f0ff', // 悬浮背景色
                    itemActiveBg: '#f0f1f3',
                    trackBg: '#f0f1f3', // 未选中项背景色
                    borderRadius: 8,
                  },
                },
              }}
            >
              <Segmented
                options={[
                  { label: '法定文书', value: 'law' },
                  { label: '事务文书', value: 'affair' }
                ]}
                value={tabKey}
                onChange={setTabKey}
                block
                style={{ width: 200, marginBottom: 12 }}
              />
            </ConfigProvider>
            {tabItems.find(item => item.key === tabKey)?.children}
          </div>
          <Form.Item label="文书标题:" name="title" rules={[{ required: true, message: '请输入文书标题' }]} style={{ marginBottom: 12 }}>
            <Input placeholder="请输入文书标题" />
          </Form.Item>
          <Form.Item label="主题词:" name="keywords" style={{ marginBottom: 12 }}>
            <Input placeholder="请输入主题词" />
          </Form.Item>
          <Form.Item label="补充说明:" name="desc" style={{ marginBottom: 12 }}>
            <TextArea rows={2} placeholder="请输入补充说明" />
          </Form.Item>
          <Form.Item label="内容篇幅:" name="length" initialValue="short" style={{ marginBottom: 12 }}>
            <Radio.Group>
              <Radio value="short">短篇</Radio>
              <Radio value="medium">中篇</Radio>
              <Radio value="long">长篇</Radio>
            </Radio.Group>
          </Form.Item>
          {currentAgent?.fileUpload === "1" && (
            <>
              <Form.Item label="参考资料:" name="refFile" valuePropName="fileList" getValueFromEvent={e => Array.isArray(e) ? e : e && e.fileList} style={{ marginBottom: 12 }}>
                <Upload
                  beforeUpload={beforeUpload}
                  maxCount={1}
                  customRequest={(options) => { customRequest(options, 'references') }}
                  showUploadList={true}
                  onRemove={() => { setReferences('') }}
                  accept=".pdf, .doc, .docx"
                >
                  <Button icon={<UploadOutlined />}>上传资料</Button>
                </Upload>
              </Form.Item>
              <Form.Item label="仿写资料:" name="imitateFile" valuePropName="fileList" getValueFromEvent={e => Array.isArray(e) ? e : e && e.fileList} style={{ marginBottom: 12 }}>
                <Upload
                  beforeUpload={beforeUpload}
                  maxCount={1}
                  customRequest={(options) => { customRequest(options, 'imitations') }}
                  showUploadList={true}
                  onRemove={() => { setImitations('') }}
                  accept=".pdf, .doc, .docx"
                >
                  <Button icon={<UploadOutlined />}>上传资料</Button>
                </Upload>
              </Form.Item>
            </>
          )}

          {recommendedPrompts && recommendedPrompts.length > 0 && (
            <Form.Item label="推荐提示词:" style={{ marginBottom: 12 }}>
              <Space wrap>
                {recommendedPrompts.map((prompt, index) => (
                  <Button
                    key={index}
                    onClick={() => form.setFieldsValue({ desc: prompt })}
                  >
                    {prompt.length > 10 ? prompt.substring(0, 10) + '...' : prompt}
                  </Button>
                ))}
              </Space>
            </Form.Item>
          )}
        </Form>
      </div>

      <div className={styles['statHub-feature-sticky-footer']}>
        <Space>
          <Button
            onClick={() => handleGenerate('outline')}
            disabled={documentStore.processing}
          >
            生成大纲
          </Button>
          <Button
            type="primary"
            onClick={() => handleGenerate('writing')}
            loading={documentStore.processing}
          >
            生成正文
          </Button>
        </Space>
      </div>
    </>
  );
};

export default inject('documentStore', 'proofreadStore')(observer(Writing)); 